import React, { useMemo, useCallback } from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  Image,
  StyleSheet,
  Dimensions,
  RefreshControl,
} from 'react-native';
import { Card } from '../types/Card';
import SecureImageView from './SecureImageView';

interface CardListProps {
  cards: Card[];
  onCardPress: (card: Card) => void;
  onEditPress: (card: Card) => void;
  onDeletePress: (card: Card) => void;
  refreshing?: boolean;
  onRefresh?: () => void;
}

const { width, height } = Dimensions.get('window');

// 响应式布局配置
const getResponsiveConfig = () => {
  const isTablet = width >= 768; // 平板判断标准
  const isLargeTablet = width >= 1024; // 大平板判断标准
  
  if (isLargeTablet) {
    return {
      numColumns: 4,
      cardSize: (width - 80) / 4, // 4列布局
      imageHeight: (width - 80) / 4,
    };
  } else if (isTablet) {
    return {
      numColumns: 3,
      cardSize: (width - 60) / 3, // 3列布局
      imageHeight: (width - 60) / 3,
    };
  } else {
    return {
      numColumns: 2,
      cardSize: (width - 48) / 2, // 2列布局
      imageHeight: (width - 48) / 2,
    };
  }
};

const CardList: React.FC<CardListProps> = React.memo(({
  cards,
  onCardPress,
  onEditPress,
  onDeletePress,
  refreshing = false,
  onRefresh,
}) => {
  // 获取响应式配置
  const config = useMemo(() => getResponsiveConfig(), []);
  
  // 构建图片显示URL - 使用 useMemo 缓存
  const getImageUrl = useCallback((path: string) => {
    if (path.startsWith('http')) {
      return path; // 网络图片
    } else {
      return `https://127.0.0.1:8553/api/images/${path}`; // 本地图片
    }
  }, []);

  // 使用 useMemo 缓存渲染函数
  const renderCard = useCallback(({ item }: { item: Card }) => (
    <View style={[styles.cardContainer, { width: config.cardSize }]}>
      <TouchableOpacity
        style={styles.card}
        onPress={() => onEditPress(item)}
        activeOpacity={0.8}
      >
        <SecureImageView
          source={{ uri: getImageUrl(item.front_image) }}
          style={[styles.cardImage, { height: config.imageHeight }]}
        />
        <View style={styles.cardInfo}>
          <Text style={styles.cardTitle} numberOfLines={2}>
            {item.title}
          </Text>
          <Text style={styles.cardText} numberOfLines={3}>
            {item.back_text}
          </Text>
        </View>
      </TouchableOpacity>
    </View>
  ), [onEditPress, getImageUrl, config]);

  // 使用 useMemo 缓存空状态组件
  const renderEmpty = useMemo(() => (
    <View style={styles.emptyContainer}>
      <Text style={styles.emptyText}>暂无卡片</Text>
      <Text style={styles.emptySubText}>点击下方按钮添加新卡片</Text>
    </View>
  ), []);

  // 使用 useMemo 缓存 keyExtractor
  const keyExtractor = useCallback((item: Card) => {
    if (typeof item.id === 'undefined' || item.id === null) {
      console.error('❌ CardList keyExtractor - item.id 为空:', item);
      return `temp_${Date.now()}_${Math.random()}`;
    }
    return item.id.toString();
  }, []);

  // 使用 useMemo 缓存样式
  const listContainerStyle = useMemo(() => styles.listContainer, []);
  const rowStyle = useMemo(() => styles.row, []);

  return (
    <FlatList
      data={cards}
      renderItem={renderCard}
      keyExtractor={keyExtractor}
      numColumns={config.numColumns}
      columnWrapperStyle={config.numColumns > 1 ? rowStyle : undefined}
      contentContainerStyle={listContainerStyle}
      ListEmptyComponent={renderEmpty}
      showsVerticalScrollIndicator={false}
      refreshControl={
        onRefresh ? (
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={['#4a90e2']}
            tintColor="#4a90e2"
          />
        ) : undefined
      }
      // 性能优化配置
      removeClippedSubviews={true}
      maxToRenderPerBatch={10}
      windowSize={10}
      initialNumToRender={6}
      getItemLayout={(data, index) => {
        const rowIndex = Math.floor(index / config.numColumns);
        const cardHeight = config.imageHeight + 80; // 图片高度 + 文字区域高度
        return {
          length: cardHeight,
          offset: cardHeight * rowIndex,
          index,
        };
      }}
    />
  );
});

CardList.displayName = 'CardList';

const styles = StyleSheet.create({
  listContainer: {
    padding: 16,
  },
  row: {
    justifyContent: 'space-between',
    marginBottom: 16,
  },
  cardContainer: {
    backgroundColor: '#ffffff',
    borderRadius: 12,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 3,
    marginBottom: 16,
    marginHorizontal: 4,
  },
  card: {
    flex: 1,
  },
  cardImage: {
    width: '100%',
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
  },
  cardInfo: {
    padding: 12,
  },
  cardTitle: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 4,
  },
  cardText: {
    fontSize: 14,
    color: '#666',
    lineHeight: 20,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 18,
    color: '#666',
    marginBottom: 8,
  },
  emptySubText: {
    fontSize: 14,
    color: '#999',
  },
});

export default CardList; 